package com.tools.cleanmaster.ui.card.factory;

import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.nineoldandroids.animation.ValueAnimator;
import com.nineoldandroids.view.ViewHelper;
import com.tools.ad.EntranceType;
import com.tools.cleanmaster.ui.card.ACardItem;
import com.tools.cleanmaster.ui.card.AdCardItem;
import com.tools.cleanmaster.ui.card.CardViewType;
import com.tools.cleanmaster.ui.card.LoadingAdCardItem;
import com.tools.cleanmaster.ui.card.viewholder.ACardViewHolder;
import com.tools.cleanmaster.ui.card.viewholder.AdCardViewHolder;
import com.tools.cleanmaster.utils.LogHelper;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

public class CardListAdapter extends ArrayAdapter<ACardItem> {

    public interface BindCardListener {
        void bind(ACardItem item);
    }

    private final List<ACardItem> mCardItemList;
    private final Map<ACardItem, ACardViewHolder> mCardViewHolderList = new HashMap<>();

    private final Activity mActivity;
    private ListView mListView;
    private static final int REMOVE_ANIMATION_DURATION = 500;
    private static final int REMOVE_ANIMATION_DELAY = 500;

    private final EntranceType mEntrance;
    private BindCardListener mBindCardListener;
    private DeleteBlankViewRunnable mDeleteBlankRunnable;
    private final Map<ACardItem, Integer> mADCardAndListViewMap = new HashMap<ACardItem, Integer>();

    private class DeleteBlankViewRunnable implements Runnable {

        private final Handler mMainHandler;
        private final HashSet<ACardItem> mCardSet = new HashSet<ACardItem>();

        public DeleteBlankViewRunnable() {
            mMainHandler = new Handler(Looper.getMainLooper());
        }

        @Override
        public void run() {
            mMainHandler.removeCallbacks(this);
            mCardItemList.removeAll(mCardSet);
            mCardSet.clear();
            mDeleteBlankRunnable = null;
            notifyDataSetChanged();
        }

        void remove(ACardItem item) {
            mCardSet.add(item);
            mMainHandler.removeCallbacks(this);
            mMainHandler.post(this);
        }
    }

    public CardListAdapter(Activity activity, ListView listView, List<ACardItem> cardItemList, EntranceType entrance) {
        super(activity, 0, cardItemList);
        mListView = listView;
        mCardItemList = cardItemList;
        mActivity = activity;
        mEntrance = entrance;
        int size = mCardItemList.size();
        int baseViewType = CardViewType.values().length;
        for (int i = 0; i < size; i++) {
            ACardItem cardItem = mCardItemList.get(i);
            if (cardItem.getCardViewType() == CardViewType.AD) {
                mADCardAndListViewMap.put(cardItem, baseViewType++);
            }
        }
    }

    public EntranceType getEntranceType() {
        return mEntrance;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ACardItem cardItem = getItem(position);
        ACardViewHolder viewHolder = mCardViewHolderList.get(cardItem);
        if (viewHolder == null) {
            viewHolder = cardItem.getCardViewType().buildCardViewHolder();
            viewHolder.initView(mActivity, cardItem, position, mEntrance);

            //缓存ViewHolder
            mCardViewHolderList.put(cardItem, viewHolder);

            //检查是否存在空白view占位的卡片，延时移除出列表
            if (cardItem instanceof AdCardItem) {
                AdCardViewHolder adCardViewHolder = (AdCardViewHolder) viewHolder;
                if (adCardViewHolder.mItemView == null) {
                    removeBlankEmptyCard(cardItem);
                }
            }
        }

        cardItem.bindCardView(mActivity, viewHolder, this, position);

        if (mBindCardListener != null) {
            mBindCardListener.bind(cardItem);
        }

        return viewHolder.mItemView;
    }

    private void removeBlankEmptyCard(ACardItem cardItem) {
        if (mDeleteBlankRunnable == null) {
            mDeleteBlankRunnable = new DeleteBlankViewRunnable();
        }
        LogHelper.d(CardDataHelper.TAG, "移除空白卡片：" + cardItem.getCardName());
        mDeleteBlankRunnable.remove(cardItem);
    }

    @Override
    public int getItemViewType(int position) {
        ACardItem cardItem = getItem(position);
        if (cardItem.getCardViewType() == CardViewType.AD) {
            return mADCardAndListViewMap.get(cardItem);
        } else {
            return cardItem.getCardViewType().ordinal();
        }
    }

    @Override
    public int getViewTypeCount() {
        return CardViewType.values().length + mADCardAndListViewMap.size();
    }

    /**
     * 卡片结果视图展示完毕后,在特定的activity声明周期触发
     */
    public final void onActivityResume() {
        for (ACardItem item : mCardItemList) {
            item.onActivityResume();
        }

        //这里不暂时不需要 notifyDataSetChanged
        //避免不必要的列表刷新，导致广告展示重复上报
        //notifyDataSetChanged();
    }

    /**
     * 卡片结果视图展示完毕后,在特定的activity声明周期触发
     */
    public final void onActivityDestroy() {
        for (ACardItem item : mCardItemList) {
            item.onActivityDestroy();
        }
    }

    // 删除卡片动画
    public void dismissAnimation(final int position) {
        if (mListView == null) {
            return;
        }
        int childCount = mListView.getChildCount();
        int first = mListView.getFirstVisiblePosition();

        int pos = position + 1 - first;
        if (pos > childCount) {
            return;
        }
        ValueAnimator animator = new ValueAnimator();
        final View v = mListView.getChildAt(pos);
        if (v == null) {
            return;
        }
        final int id = position;
        final int h = v.getHeight();
        final int w = v.getWidth();
        animator.setFloatValues(0, 1);
        animator.setDuration(REMOVE_ANIMATION_DURATION);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            private boolean mDeletedFlag = false;

            @Override
            public void onAnimationUpdate(ValueAnimator arg0) {
                float f = (Float) arg0.getAnimatedValue();
                animateVisibleItemOut(v, w, h, f);
                if (f >= 0.9 && !mDeletedFlag) { // 动画进行到90%的时候刷新listView，避免抖动问题
                    if (mListView != null) {
                        if (id >= 0 && id < mCardItemList.size()) {
                            mListView.removeViewInLayout(v);
                            remove(mCardItemList.remove(id));
                            mDeletedFlag = true;
                        }
                    }
                }
            }
        });
        animator.setStartDelay(REMOVE_ANIMATION_DELAY);
        animator.start();
    }

    // 移除卡片，ListView整体上移
    private void animateVisibleItemOut(View v, int w, int h, float f) {
        if (mListView == null) {
            return;
        }
        AbsListView.LayoutParams layoutParams = (AbsListView.LayoutParams) v.getLayoutParams();
        layoutParams.height = (int) ((1 - f) * h);
        v.setLayoutParams(layoutParams);
        ViewHelper.setAlpha(v, 1 - f);
        ViewHelper.setTranslationX(v, -w * f);
    }
}
